package com.mechat.ui

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.provider.Settings
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.mechat.Constant
import com.mechat.R
import com.mechat.dialog.NotificationPermissionDialog
import com.mechat.entity.UpdateApkEntity
import io.rong.imkit.event.EnumEventTag
import com.mechat.socket.event.EventFactory
import com.mechat.socket.event.UnifyEvent
import com.mechat.socket.netty.NettyClient
import com.mechat.ui.my.MyFragment
import com.mechat.util.HandlerUtils
import com.mechat.util.PermissionUtils
import com.mechat.util.SystemUtils
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.mvp.BasePresenterImpl
import com.mechat.App
import com.mechat.BuildConfig
import com.mechat.dialog.RemindDialog
import com.mechat.dialog.UpdateApkDialog
import com.mechat.ui.chats.ChatsFragment
import com.mechat.util.HttpRequest
import com.sunday.eventbus.SDEventManager
import io.rong.imkit.RongIM
import io.rong.imkit.SpName
import io.rong.imkit.utils.JsonUtils
import io.rong.imlib.model.UserInfo
import org.json.JSONException
import org.json.JSONObject
import razerdp.basepopup.BasePopupWindow
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.Executors


/**
 * 作者：
 * 时间：
 * 描述：主页
 */
class HomePresenter : BasePresenterImpl<HomeContract.View>(), HomeContract.Presenter,
    HandlerUtils.OnReceiveMessageListener {

    private val Permission_Request = 10001
    private var index = 0
    private var chatsFragment: Fragment? = null
    private var myFragment: Fragment? = null
    private var remindDialog:RemindDialog?=null
    private var fragments = arrayListOf<Fragment>()
    var handel = HandlerUtils.HandlerHolder(this)
    private var tableTitle= listOf("Chats","Me")
    private var selectImage =
        listOf(
            R.drawable.table_chats_select,
            R.drawable.table_mine_select,
        )
    private var noSelectImage =
        listOf(
            R.drawable.table_chats_unselect,
            R.drawable.table_mine_unselect,
        )

    private var CHATS_FRAGMENT_KEY = "chatsFragment"
    private var MY_FRAGMENT_KEY = "myFragment"
    private var LASTINDEX_KEY = "lastIndex"
    fun onCreate(savedInstanceState: Bundle?, homeActivity: HomeActivity) {
        savedInstanceState?.let {
            chatsFragment = homeActivity.supportFragmentManager.getFragment(
                savedInstanceState,
                CHATS_FRAGMENT_KEY
            ) as ChatsFragment

            if (homeActivity.supportFragmentManager.getFragment(
                    savedInstanceState,
                    MY_FRAGMENT_KEY
                ) != null
            ) {
                myFragment = homeActivity.supportFragmentManager.getFragment(
                    savedInstanceState,
                    MY_FRAGMENT_KEY
                ) as MyFragment
            }
            if (savedInstanceState.getInt(LASTINDEX_KEY) != null) {
                index = savedInstanceState.getInt(LASTINDEX_KEY)
            }
        }

        mView?.apply {
            if (chatsFragment == null) {
                chatsFragment = ChatsFragment()
            }

            if (myFragment == null) {
                myFragment = MyFragment()
            }
            if (!fragments.contains(chatsFragment)) {
                fragments.add(chatsFragment as ChatsFragment)

            }
            if (!fragments.contains(myFragment)) {
                fragments.add(myFragment as MyFragment)
            }


            for (i in tabs.indices) {
                setTab(i, tabIvs,tabTxts)
                tabs[i].setOnClickListener {
                    this@HomePresenter.index = i
                    setTabClick(i, tabIvs,tabTxts)
                    fm.toggle(fragmentId.id, null, fragments[i])
                }
            }
            goIndex(index)
        }
        showNotificationDialog()

        startSocket(if(BuildConfig.DEBUG)"ws://120.26.196.82:9002/ws" else "ws://165.154.163.79:9002/ws")
        handel.sendEmptyMessage(1)
    }


    fun onSaveInstanceState(outState: Bundle, homeActivity: HomeActivity) {
        if (chatsFragment != null) {
            if(chatsFragment!!.activity != null){
                val fragment = homeActivity.supportFragmentManager.findFragmentByTag(CHATS_FRAGMENT_KEY)
                if (fragment ==null) {
                    homeActivity.supportFragmentManager.putFragment(
                        outState,
                        CHATS_FRAGMENT_KEY,
                        chatsFragment!!
                    )
                }
            }

        }


        if (myFragment != null) {
            if (myFragment!!.activity!= null) {
                val fragment = homeActivity.supportFragmentManager.findFragmentByTag(MY_FRAGMENT_KEY)
                if (fragment == null) {
                    homeActivity.supportFragmentManager.putFragment(
                        outState,
                        MY_FRAGMENT_KEY,
                        myFragment!!
                    )
                }
            }
        }
        outState.putInt(LASTINDEX_KEY, index)
    }

    /**
     * 检查更新
     */
    fun checkUpdate() {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setGet(Constant.user_apk_update_url)
                requestBody.add("versionCode", SystemUtils.getVersionCode(mActivity))
                requestBody.add("appCode", "chat01")
            }
        }, object : SDOkHttpResoutCallBack<UpdateApkEntity>(false) {
            override fun onSuccess(entity: UpdateApkEntity) {
                if (entity.data.updateFlag) {
                    val updateApkDialog = UpdateApkDialog(
                        mActivity,
                        entity.data.upGradationDesc,
                        entity.data.updateType
                    )
                    updateApkDialog.showPopupWindow()
                    updateApkDialog.onDismissListener = object :
                        BasePopupWindow.OnDismissListener() {
                        override fun onDismiss() {
                            if(entity.data.updateType==1) {
                                RongIM.getInstance().logout()
                                mActivity.finish()
                            }
                        }

                    }
                }
            }
        }, isShowDialog = false)
    }

    private fun setTab(index: Int, tabIvs: List<ImageView>, tabTxts: List<TextView>) {
        BaseConfig.getInstance.setInt(SpName.homeIndex, index)
        for (i in tabIvs.indices) {
            tabTxts[i].text = tableTitle[i]
            if (index == i) {
                tabIvs[i].setImageResource(selectImage[i])
                tabTxts[i].setTextColor(ContextCompat.getColor(mActivity,R.color.color_4699FF))
            } else {
                tabTxts[i].setTextColor(ContextCompat.getColor(mActivity,R.color.color_62656A))
                tabIvs[i].setImageResource(noSelectImage[i])
            }
        }
    }

    private fun setTabClick(index: Int, tabIvs: List<ImageView>, tabTxts: List<TextView>) {
        BaseConfig.getInstance.setInt(SpName.homeIndex, index)
        for (i in tabIvs.indices) {
            tabTxts[i].text = tableTitle[i]
            if (index == i) {
                HttpRequest.commonNotify("BottomNavigation",tabTxts[i].text.toString())
                tabIvs[i].setImageResource(selectImage[i])
                tabTxts[i].setTextColor(ContextCompat.getColor(mActivity,R.color.color_4699FF))
            } else {
                tabIvs[i].setImageResource(noSelectImage[i])
                tabTxts[i].setTextColor(ContextCompat.getColor(mActivity,R.color.color_62656A))
            }
        }
    }

    fun showNotificationDialog() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && PermissionUtils.lacksPermission(mActivity, Manifest.permission.POST_NOTIFICATIONS)) {
            NotificationPermissionDialog(
                mActivity,
                object : NotificationPermissionDialog.OnListener {
                    override fun onGrantedListener() {
                    }

                    override fun onDeniedListener() {
                        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                        val uri = Uri.fromParts("package", mActivity.packageName, null)
                        intent.data = uri
                        mActivity.startActivityForResult(intent, Permission_Request)
                    }

                }).showPopupWindow()
        }
    }

    override fun goIndex(Index: Int) {
        mView?.apply {
            this@HomePresenter.index = Index
            setTab(Index, tabIvs,tabTxts)
            fm.toggle(fragmentId.id, null, fragments[Index])
        }
    }


    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == Permission_Request) {
            Log.e("~~~", "onActivityResult: ${PermissionUtils.lacksPermission(mActivity, Manifest.permission.POST_NOTIFICATIONS)}" )
            if (PermissionUtils.lacksPermission(mActivity, Manifest.permission.POST_NOTIFICATIONS)){
                mActivity.finish()
            }

        } else {
            fragments[index].onActivityResult(requestCode, resultCode, data)
        }
    }


    fun startSocket(hostUrl: String) {
        Executors.newSingleThreadExecutor().execute {
            Log.e("NettyClient", "run: $hostUrl")
            val nettyClient: NettyClient = NettyClient.getInst()
            nettyClient.setContext(mActivity)
            nettyClient.hostUrl = hostUrl
            // 启动并初始化
            var tk = ""
            try {
                tk = BaseConfig.getInstance.getString(SpName.userCode, "")
                nettyClient.token = tk
            } catch (e: Exception) {
                Log.i("HomeFragment", "Get token exception")
            }
            if (!nettyClient.isConnectFlag) {
                nettyClient.startConnectServerAlways()
            }
        }
    }


    /**
     *
     */
    private fun getSocketInfo() {
        try {
            val queue: ConcurrentLinkedQueue<UnifyEvent> = EventFactory.getQuotesInstance()
            while (!queue.isEmpty()) {
                //从队列取出一个元素 排队的人少一个
                val poll: UnifyEvent = queue.poll()
                val body: String = poll.body
                val bizCode: String = poll.bizCode
                when {
                    "M20001".equals(bizCode, ignoreCase = true) -> {
                        if (JsonUtils.isJSON(body)) {
                            SDEventManager.post(body,EnumEventTag.MODEL_LIST_REFRESH.ordinal)
                        }
                    }
                    "M20002".equals(bizCode, ignoreCase = true) -> {
                        if (JsonUtils.isJSON(body)) {
                            SDEventManager.post(body,EnumEventTag.MODEL_LIST_ONLINE_REFRESH.ordinal)
                        }
                    }
                    "M20003".equals(bizCode, ignoreCase = true) -> {
                        if (BaseConfig.getInstance.getString(SpName.token,"")!="") {
                            if (remindDialog == null) {
                                remindDialog = RemindDialog(App().getApplicationContexts())
                                remindDialog?.showPopupWindow()
                                remindDialog?.onDismissListener =
                                    object : BasePopupWindow.OnDismissListener() {
                                        override fun onDismiss() {
                                            remindDialog = null
                                        }
                                    }
                            }
                        }
                    }
                    "M20004".equals(bizCode, ignoreCase = true) -> {
                        if (JsonUtils.isJSON(body)) {
                            Log.e("~~~", "getSocketInfo: $body" )
                            SDEventManager.post(body,EnumEventTag.MODEL_LIST_REMOVE_UNREAD_REFRESH.ordinal)
                        }
                    }

                }
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    override fun handlerMessage(msg: Message?) {
        when (msg?.what) {
            1 -> {
                getSocketInfo()
                handel.sendEmptyMessageDelayed(1, 5000)

            }
        }
    }

}